
import { Channel, UserChannelResponse } from '@/types/data.d.'
import request from '@/utils/request'
import _ from 'lodash'
import { AppThunk } from '../index'
import { addUserChannel, delUserChannel, setChannelList, setUserChannelList } from '../modules/home'
// 3. 异步action
// 登录过获取登录人数据 
// 没登录获取所有数据
export const getChannelListAction = (payload?: unknown): AppThunk => {
  return async (dispatch, getState) => {
    // 获取所有数据
    const all: UserChannelResponse = await request.get('/channels')
    console.log(all.data.channels)
    const { userChannel } = getState().home
    dispatch(setChannelList(_.differenceBy(all.data.channels, userChannel, 'id')))
  }
}
export const getUserChannelListAction = (payload?: unknown): AppThunk => {
  return async (dispatch, getState) => {
    const res: UserChannelResponse = await request.get('/user/channels')
    dispatch(setUserChannelList(res.data.channels))
  }
}
/**
 * 
 * @param payload 用户传入完整内容 {id，name}
 * @returns 
 */
export const delUserChannelListAction = (payload: Channel): AppThunk => {
  return async (dispatch, getState) => {
    await request.delete('/user/channels/' + payload?.id)
    dispatch(delUserChannel(payload))
  }
}
export const addUserChannelListAction = (payload: Channel): AppThunk => {
  return async (dispatch, getState) => {
    await request.patch('/user/channels/', { channels: [payload] })
    dispatch(addUserChannel(payload))
  }
}
